﻿// mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "virtualdevice.h"
#include <QMessageBox>
#include <QDateTime>
#include <QScrollBar>
#include <QThread>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("Virtual RF Devices Server");
    updateDeviceList();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initDefaultDevice()
{
    QString ip = "127.0.0.1";
    for (int var = 0; var < 5; ++var) {
        quint16 port = 5001 + var;
        ui->portSpinBox->setValue(port);
        QString key = QString("%1:%2").arg(ip).arg(port);
        QSharedPointer<VirtualDevice> device(new VirtualDevice(ip, port));
        // 连接设备的日志信号到主窗口的槽函数
        connect(device.data(), &VirtualDevice::logMessage, this, &MainWindow::appendToLog);

        m_devices[key] = device;
        updateDeviceList();
        ui->logTextEdit->append(QString("[%1] Device added: %2").arg(QTime::currentTime().toString("hh:mm:ss.zzz")).arg(key));
        QThread::msleep(200);
    }
}

void MainWindow::on_addDeviceButton_clicked()
{
    QString ip = ui->ipLineEdit->text().trimmed();
    quint16 port = static_cast<quint16>(ui->portSpinBox->value());

    if (ip.isEmpty()) {
        QMessageBox::warning(this, "Input Error", "IP address cannot be empty.");
        return;
    }

    QString key = QString("%1:%2").arg(ip).arg(port);
    if (m_devices.contains(key)) {
        QMessageBox::information(this, "Duplicate", "A device with this IP and port already exists.");
        return;
    }

    QSharedPointer<VirtualDevice> device(new VirtualDevice(ip, port));
    // 连接设备的日志信号到主窗口的槽函数
    connect(device.data(), &VirtualDevice::logMessage, this, &MainWindow::appendToLog);

    m_devices[key] = device;
    updateDeviceList();
    ui->logTextEdit->append(QString("[%1] Device added: %2").arg(QTime::currentTime().toString("hh:mm:ss.zzz")).arg(key));
}

void MainWindow::on_removeDeviceButton_clicked()
{
    QString key = getCurrentDeviceKey();
    if (key.isEmpty())
        return;

    auto it = m_devices.find(key);
    if (it != m_devices.end()) {
        if (it.value()->isRunning()) {
            int ret = QMessageBox::question(this, "Device Running",
                                            QString("Device %1 is currently running. Stop it and remove?").arg(key));
            if (ret == QMessageBox::Yes) {
                it.value()->stop();
            } else {
                return;
            }
        }
        m_devices.erase(it);
        updateDeviceList();
        ui->logTextEdit->append(QString("[%1] Device removed: %2").arg(QTime::currentTime().toString("hh:mm:ss.zzz")).arg(key));
    }
}

void MainWindow::on_startAllButton_clicked()
{
    if (m_devices.isEmpty()) {
        QMessageBox::information(this, "No Devices", "No devices to start.");
        return;
    }

    int startedCount = 0;
    for (auto it = m_devices.begin(); it != m_devices.end(); ++it) {
        if (!it.value()->isRunning()) {
            if (it.value()->start()) {
                startedCount++;
            }
        }
    }
    ui->logTextEdit->append(QString("[%1] Started %2 device(s).").arg(QTime::currentTime().toString("hh:mm:ss.zzz")).arg(startedCount));
}

void MainWindow::on_stopAllButton_clicked()
{
    int stoppedCount = 0;
    for (auto it = m_devices.begin(); it != m_devices.end(); ++it) {
        if (it.value()->isRunning()) {
            it.value()->stop();
            stoppedCount++;
        }
    }
    ui->logTextEdit->append(QString("[%1] Stopped %2 device(s).").arg(QTime::currentTime().toString("hh:mm:ss.zzz")).arg(stoppedCount));
}

void MainWindow::appendToLog(const QString &message)
{
    ui->logTextEdit->append(message);
    // 自动滚动到底部
    QScrollBar *sb = ui->logTextEdit->verticalScrollBar();
    sb->setValue(sb->maximum());
}

// --- 辅助函数 ---

QString MainWindow::getCurrentDeviceKey() const
{
    QListWidgetItem *currentItem = ui->deviceListWidget->currentItem();
    if (!currentItem) {
        QMessageBox::information(const_cast<MainWindow *>(this), "No Selection", "Please select a device from the list.");
        return QString();
    }
    return currentItem->text().split(" (")[0]; // 提取 "IP:Port" 部分
}

void MainWindow::updateDeviceList()
{
    ui->deviceListWidget->clear();
    for (auto it = m_devices.constBegin(); it != m_devices.constEnd(); ++it) {
        QString status = it.value()->isRunning() ? " (Running)" : " (Stopped)";
        ui->deviceListWidget->addItem(it.key() + status);
    }
}

// --- 响应设置槽函数 ---
void MainWindow::on_setResponseButton_clicked()
{
    QString key = getCurrentDeviceKey();
    if (key.isEmpty())
        return;

    QString command = ui->commandLineEdit->text().trimmed();
    QString response = ui->responseLineEdit->text();

    if (command.isEmpty()) {
        QMessageBox::warning(this, "Input Error", "Command cannot be empty.");
        return;
    }

    auto it = m_devices.find(key);
    if (it != m_devices.end()) {
        it.value()->setResponse(command, response);
        ui->logTextEdit->append(QString("[%1] Set response for '%2' on %3: %4")
                                    .arg(QTime::currentTime().toString("hh:mm:ss.zzz"))
                                    .arg(command)
                                    .arg(key)
                                    .arg(response));
    }
}

void MainWindow::on_setDefaultResponsesButton_clicked()
{
    QString key = getCurrentDeviceKey();
    if (key.isEmpty())
        return;

    auto it = m_devices.find(key);
    if (it != m_devices.end()) {
        QSharedPointer<VirtualDevice> device = it.value();
        quint16 port = device->getPort();

        // 核心逻辑：根据端口设置默认 readPower 响应
        if (port == 5003) {
            device->setResponse("FETCH1?", "30");
            ui->logTextEdit->append(QString("[%1] Set default response for 'readPower' on %2: 30")
                                        .arg(QTime::currentTime().toString("hh:mm:ss.zzz"))
                                        .arg(key));
        } else {
            device->setResponse("FETCH1?", "0");
            ui->logTextEdit->append(QString("[%1] Set default response for 'readPower' on %2: 0")
                                        .arg(QTime::currentTime().toString("hh:mm:ss.zzz"))
                                        .arg(key));
        }
    }
}
